package com.anmi.transfer.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.anmi.alfred.entity.TransferCaseOperationResult;
import com.anmi.alfred.service.concreteservice.CaseOperationIndexService;
import com.anmi.transfer.schedule.CaseOperationSchedule;
import com.anmi.transfer.service.TransferCaseOperationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping(value = "/api")
public class CaseOperationSyncController {

  @Autowired CaseOperationSchedule caseOperationSchedule;
  @Autowired TransferCaseOperationService transferCaseOperationService;
  @Autowired CaseOperationIndexService caseOperationIndexService;

  @RequestMapping(value = "/caseOperationSync")
  public String caseOperationSync() throws InterruptedException {
    return caseOperationSchedule.syncMysqlToES();
  }

  @GetMapping(value = "/caseOperationSync/one/{id}")
  public String caseOperationOneIndex(@PathVariable Long id) {
    TransferCaseOperationResult caseOperationResult =
        transferCaseOperationService.selectByCaseOperationId(id);
    if (caseOperationResult != null) {
      caseOperationIndexService.indexSync(
          TransferCaseOperationResult.ALIAS_NAME,
          String.valueOf(id),
          JSON.toJSONString(caseOperationResult, SerializerFeature.WriteNullStringAsEmpty));
      return "Writing to Elasticsearch Successfully!";
    }
    return "No data in MySQL or fail to Elasticsearch!";
  }
}
